﻿<!DOCTYPE html>
<html>
<head>
	<title>生产指令</title>

	<meta name="keywords" content="keyword1,keyword2,keyword3">
	<meta name="description" content="this is my page">
	<meta name="content-type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="/static/plugin/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="/static/css/public.css" media="all" />
	<script type="text/javascript" src="/static/plugin/jquery/jquery-3.3.1.js"></script>
	<script type="text/javascript" src="/static/plugin/layui/layui.js"></script>
	<script type="text/javascript" src="/static/js/public.js"></script>
	<script type="text/javascript" src="/static/js/base.js"></script>
	<style type="text/css">
		.xing
		{
			color: red;
			float: left;
			display: block;
			width: 0.1%;
			margin-top:-25px;
			margin-left: 83%;
			font-size: 24px;
		}
	</style>
</head>
<script type="text/javascript">
    $(document).on('keydown','[lay-id="productAddTable"] .layui-table-edit',function(e){
        var td = $(this).parent('td'),
            tr = td.parent('tr'),
            trs = tr.parent().parent().find('tr'),
            tr_index = tr.index(),
            td_index = td.index(),
            td_last_index = tr.find('[data-edit="text"]:last').index(),
            td_first_index = tr.find('[data-edit="text"]:first').index();
        switch(e.keyCode){
            case 13:
            case 39:
                td.nextAll('[data-edit="text"]:first').click();
                if(td_index == td_last_index){
                    tr.next().find('td').eq(td_first_index).click();
                    if(tr_index == trs.length-1){
                        trs.eq(0).find('td').eq(td_first_index).click();
                    }
                }
                setTimeout(function(){
                    $('.layui-table-edit').select()
                },0)
                break;
            case 37:
                td.prevAll('[data-edit="text"]:first').click();
                setTimeout(function(){
                    $('.layui-table-edit').select()
                },0)
                break;
            case 38:
                tr.prev().find('td').eq(td_index).click();
                setTimeout(function(){
                    $('.layui-table-edit').select()
                },0)
                break;
            case 40:
                tr.next().find('td').eq(td_index).click();
                setTimeout(function(){
                    $('.layui-table-edit').select()
                },0)
                break;
        }
    })
</script>
<body  class="layui-anim">
<div class="x-nav">
	    <span class="layui-breadcrumb">
	        <a href="">首页</a>
	        <a>
	            <cite>生产指令</cite>
	        </a>
	    </span>
</div>
<div class="x-body">
	<div class="layui-row" style="margin-bottom: 18px">
		<form class="layui-form">
			<div class="layui-inline">
				<div class="layui-input-inline">
					<input type="text" id="keyword01" class="layui-input searchVal" placeholder="请输入通知单编号" />
				</div>
				<div class="layui-input-inline">
					<input class="layui-input" id="startTime" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					-<input class="layui-input" id="endTime" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
				</div>
				<button type="button" class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
			</div>
		</form>
	</div>
	<xblock>
		<button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
		<button class="layui-btn layui-btn-danger" id="del"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	</xblock>
	<table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	<table class="layui-hide" id="tableListDetail" lay-filter="tableListDetail"></table>
</div>

<script type="text/html" id="productAddRowToolbar">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="proDel">删除</a>
</script>

<!-- 新增框 -->
<div id="addDivID" hidden="hidden">
	<form class="layui-form" id="addFormID">
		<xblock>
			<table style="margin-top: 8px;">
				<tr>
					<td><label class="layui-form-label">通知单编号</label></td>
					<td>
						<input readonly class="layui-input" id="tonumber" name="tonumber" style="width: 160px; color: gray" placeholder="请输入收货单号" lay-filter="only">
						<input type="hidden" id="toid" name="toid">
					</td>
					<td>
						<label class="layui-form-label">供应商</label></td>
					<td>
						<div class="layui-input-inline" style="width:160px">
							<select class="layui-input" name="sid" id="sid" lay-filter="sid">
								<option value="">请选择供应商</option>
							</select>
						</div>
						<div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
						<input type="hidden" id="text">
					</td>
					<td>
                        <button type="button" id="addProduct" class="layui-btn layui-btn-normal">选择物料</button>
                    </td>
				</tr>
				<tr style="height:10px"></tr>
			</table>
		</xblock>
		<table id="productAddTable" lay-filter="productAddTable"></table>
		<xblock>
			<div align="center">
				<button type="button" class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm">提交</button>
				&emsp;&emsp;&emsp;&emsp;
				<button class="layui-btn layui-btn-primary">取消</button>
			</div>
		</xblock>
	</form>
</div>
<!-- 产品选择框 -->
<div id="productDiv" hidden="hidden">
	<form class="layui-form">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<td>
							<input class="layui-input" name="materiel_num_search" id="materiel_num_search" placeholder="请输入图号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel" data-type="reload1"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable" lay-filter="productTable"></table>
		<input id="dtim" type="hidden">
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
		</xblock>
	</form>
</div>
<script type="text/javascript">
	layui.config({
        base: '/static/module/'
    }).extend({
        layuiTableColumnEdit:'js/layuiTableColumnEdit'
    }).use(['table','layer','upload','form','laydate','layuiTableColumnEdit'], function(){
		var table = layui.table;
		var layer = layui.layer;
		var form = layui.form;
		var laydate = layui.laydate;

        var layuiTableColumnEdit = layui.layuiTableColumnEdit;
		/**
		 * 新增生产指令时单元格下拉框使用
		*/
		//紧急程度
        var selectUrgent = [
            {name:0,value:"正常"},
            {name:1,value:"紧急"},
        ];
        //特殊要求
        var selectMaSpecialRequirements = [
            {name:0,value:"无"},
            {name:1,value:"二遍漆"},
        ];
        //是否分拣
        var selectTodremark = [
            {name:0,value:"是"},
            {name:1,value:"否"},
        ];
        //起始位置
        var selectTodremark1 = [
            {name:"FJ",value:"分拣区"},
            {name:"QCL",value:"前处理区"},
            {name:"PT",value:"喷涂线"},
        ];

        //起始位置
        var arrSelect = [
            {todremark1:"FJ",todremark:0,urgent:0},
            {todremark1:"QCL",todremark:1,urgent:1},
            {todremark1:"PT",todremark:1,urgent:1},
        ];

        var rowData; //当前行数据

		function selectFindValueByName(arr,name) {
            var data = arr.filter(function(item){
                return item.name == name;
            })
			if(data.length == 1){
                return data[0].value
			}else{
                return ""
			}
        }

        /********************************* 开始时间结束时间设置 star *********************************/
        //日期时间范围
        var minListDate = "1000-01-01 00:00:00";//最小可选时间，例：1990-02-01
        var maxListDate = "3000-12-31 23:59:59";//最大可选时间，例：2200-12-31
		//结束时间
		var enddate = laydate.render({
			elem: "#endTime",
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
			min: minListDate,
			max: maxListDate,
			done: function (val, date) {
				if (date && date.year){
                    //设置结束时间 设置开始时间的最大值为结束时间
                    begindate.config.max = {
                        year: date.year,
                        month: date.month - 1,//必须减1才是正确值
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
				}else {
					//清除结束值    设置开始时间最大值
					var dateInit = new Date(maxListDate.replace(/-/g, "/"));
                    begindate.config.max = {
                        year: dateInit.getFullYear(),
                        month: dateInit.getMonth(),
                        date: dateInit.getDate(),
                        hours: dateInit.getHours(),
                        minutes: dateInit.getMinutes(),
                        seconds: dateInit.getSeconds()
                    };
				}
			}
		});
		//开始时间
		var begindate = laydate.render({
			elem: "#startTime",
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
			min: minListDate,
			max: maxListDate,
			done: function (val, date) {
				if (date && date.year){
					//设置开始时间 设置结束时间的最小值为开始时间
                    enddate.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
				}else {
					//清除开始值 ，设置结束值最小值
					var dateInit = new Date(minListDate.replace(/-/g, "/"));
                    enddate.config.min = {
                        year: dateInit.getFullYear(),
                        month: dateInit.getMonth(),
                        date: dateInit.getDate(),
                        hours: dateInit.getHours(),
                        minutes: dateInit.getMinutes(),
                        seconds: dateInit.getSeconds()
                    };
				}
			}
		});
		/********************************* 开始时间结束时间设置  end*********************************/
		var $ = layui.jquery, active = {
			reload:function () {
				var whereStr = ""
				var keyword01 = $("#keyword01").val();
				var startTime = $("#startTime").val();
				if(startTime != ""){
					whereStr += " and tocreateTime >= '''" + startTime+"'''"
				}
				var endTime = $("#endTime").val();
				if(endTime != ""){
					whereStr += " and tocreateTime <= '''" + endTime+"'''"
				}
				table.reload('contenttable',{
					method:'get',
					where:{"whereStr":whereStr,"tonumber":keyword01}
					,page: {
						curr: 1//重新从第 1 页开始
					}
				});
			},
            reload1:function () {
                var materiel_num_search = $.trim($("#materiel_num_search").val());
				table.reload('productTable',{
					method:'get',
					where:{"material.maNumber":materiel_num_search},
					page: {
						curr: 1//重新从第 1 页开始
					}
				});
            },
		}

		$('.layui-btn').on('click', function(){
			var type = $(this).data('type');
			active[type] ? active[type].call(this) : '';
		});
		table.render({
			elem: '#tableList'
			,url:'/transitOrder/transitOrderList'
			,title: '生产指令'
			,id :'contenttable'
			,limits:[10,20,30]
			,toolbar: '#toolbar'
			,request: {   //如果无需自定义请求参数，可不加该参数
				pageName: 'page' //页码的参数名称，默认：page
				,limitName: 'pageSize' //每页数据量的参数名，默认：limit
			}
			,response: {   //如果无需自定义数据响应名称，可不加该参数
				countName: 'total' //规定数据总数的字段名称，默认：count
				,dataName: 'rows' //规定数据列表的字段名称，默认：data
			}
			,cols: [
				[
					{type: 'checkbox', fixed: 'left'}
					,{field:'toid', title:'序号', sort: true, type:'numbers', width: 60}
					,{field:'tonumber', title:'通知单编号'}
                    ,{field:'supplier.sname', title:'供应商名称'
						,templet: function(d){
							var value = "";
							if(d.supplier != null){
								value = d.supplier.sname
							}
							return value;
						},
					}
					,{field:'tostare', title:'状态'
						,templet: function(d){
							var value = "";
							if(d.tostare == 0){
								value = "未操作"
							}else if(d.tostare == 1){
								value = "已操作"
							}else if(d.tostare == 2){
								value = "已收货"
							}
							return value;
						}, //hide:true,
					}
					,{field:'tocreateMan', title:'录单人'}
					,{field:'tocreateTime', title:'日期'
						,templet: function(d){
							var value = d.tocreateTime;
							return formatTime(value,"yyyy-MM-dd HH:mm");
						},
					}
				]
			]
			,page: true
			,done : function(){
				$('th').css({
					'background-color': '#009688', 'color': '#fff','font-weight':'bold',
				})
			}
		});
		table.render({
			elem: '#tableListDetail'
			,title: '生产指令详情'
			,id :'contenttableDetail'
			,data:new Array()
			,limits:[10,20,30]
			,toolbar: '#toolbar'
			,request: {   //如果无需自定义请求参数，可不加该参数
				pageName: 'page' //页码的参数名称，默认：page
				,limitName: 'pageSize' //每页数据量的参数名，默认：limit
			}
			,response: {   //如果无需自定义数据响应名称，可不加该参数
				countName: 'total' //规定数据总数的字段名称，默认：count
				,dataName: 'rows' //规定数据列表的字段名称，默认：data
			}
			,cols: [
				[
					{type: 'checkbox', fixed: 'left'}
					,{field:'todid', title:'序号', sort: true, type:'numbers', width: 60}
					,{field:'material.maNumber', title:'图号'
						,templet: function(d){
							var value = "";
							if(d.material != null){
								value = d.material.maNumber
							}
							return value;
						},
					}
                    ,{field:'material.maName', title:'产品名称'
						,templet: function(d){
							var value = "";
							if(d.material != null){
								value = d.material.maName
							}
							return value;
						},
					}
					,{field:'todnum', title:'数量'}
					,{field:'workshop', title:'加工车间'}
					,{field:'todSprayingRequirements', title:'喷涂要求'}
					,{field:'todSpecialRequirements', title:'特殊要求'
						,templet: function(d){
							var value = "";
                        	value = selectFindValueByName(selectMaSpecialRequirements,d.todSpecialRequirements)
							return value;
						},
					}
					,{field:'urgent', title:'紧急程度'
						,templet: function(d){
							var value = "";
                        	value = selectFindValueByName(selectUrgent,d.urgent)
							return value;
						},
					}
                    ,{field:'todremark', title:'是否分拣'
						,templet: function(d){
							var value = "";
                        	value = selectFindValueByName(selectTodremark,d.todremark)
							return value;
						},
					}
					,{field:'todremark1', title:'起始位置'
						,templet: function(d){
							var value = "";
                        	value = selectFindValueByName(selectTodremark1,d.todremark1)
							return value;
						},
					}
					,{field:'material.remark01', title:'备注1'
						,templet: function(d){
							var value = "";
							if(d.material != null){
								value = d.material.remark01
							}
							return value;
						},
					}
					,{field:'material.remark02', title:'备注2'
						,templet: function(d){
							var value = "";
							if(d.material != null){
								value = d.material.remark02
							}
							return value;
						},
					}
				]
			]
			,page: true
			,done : function(){
				$('th').css({
					'background-color': '#009688', 'color': '#fff','font-weight':'bold',
				})
			}
		});
		table.render({
			elem: '#productAddTable'
            ,defaultToolbar:['filter', 'print']
			,cols: [
				[
					{type: 'checkbox', fixed: 'left'}
					,{field:'maId', title:'maId', align:'center', hide:true}
					,{field:'todid', title:'序号', sort: true, type:'numbers', width: 60}
					,{field:'maNumber', title:'图号'}
                    ,{field:'maName', title:'产品名称'}
					,{field:'todnum', edit: 'text',title:'数量'}
					//,{field:'workshop', edit: 'text',title:'加工车间'}
					,{field:'maSprayingRequirements',edit: 'text', title:'喷涂要求'}
					,{field:'maSpecialRequirements',title:'特殊要求'}
					,{field:'urgent', title:'紧急程度'}
					,{field:'todremark', title:'是否分拣'}
					,{field:'todremark1', title:'起始位置'}
                    , {
						fixed: 'right',
						title:'操作',
						toolbar: '#productAddRowToolbar',
						align:'center',
						unresize: true,
						width:100
					}
				]
			]
			,limit:Number.MAX_VALUE
            ,page: false
            ,height: 400
            ,done : function(res, curr, count){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
                layuiTableColumnEdit.render({
                    id:'#productAddTable',
                    type:'select',
                    field:'urgent',
                    data:selectUrgent,
                    callback:function (obj) {
                        console.log(obj.select); //下拉选项数据
                        console.log(obj.td); //当前单元格（td）DOM元素
                        //把选择的数据更新到行数据中
						var data = rowData.data;
                        var oldData =  table.cache["productAddTable"];
                        var i = rowData.tr.attr('data-index');
                        data.urgent = parseInt(obj.select.name);
                        oldData.splice(i,1,data)
                        table.reload('productAddTable',{
                            data : oldData
                        });
                        //rowData.update({urgent:parseInt(obj.select.name)});
                        //把选择的显示数据更新到单元格中显示
                        obj.update();
                    }
                });
                layuiTableColumnEdit.render({
                    id:'#productAddTable',
                    type:'select',
                    field:'todremark',
                    data:selectTodremark,
                    callback:function (obj) {
                        console.log(obj.select); //下拉选项数据
                        console.log(obj.td); //当前单元格（td）DOM元素
                        //把选择的数据更新到行数据中
						var data = rowData.data;
                        var oldData =  table.cache["productAddTable"];
                        var i = rowData.tr.attr('data-index');
                        data.todremark = parseInt(obj.select.name);
                        oldData.splice(i,1,data)
                        table.reload('productAddTable',{
                            data : oldData
                        });
                        //rowData.update({urgent:parseInt(obj.select.name)});
                        //把选择的显示数据更新到单元格中显示
                        obj.update();
                    }
                });
                layuiTableColumnEdit.render({
                    id:'#productAddTable',
                    type:'select',
                    field:'todremark1',
                    data:selectTodremark1,
                    callback:function (obj) {
                        console.log(obj.select); //下拉选项数据
                        console.log(obj.td); //当前单元格（td）DOM元素
                        //把选择的数据更新到行数据中
						var data = rowData.data;
                        var oldData =  table.cache["productAddTable"];
                        var i = rowData.tr.attr('data-index');
                        data.todremark1 = obj.select.name;
                        oldData.splice(i,1,data)
                        table.reload('productAddTable',{
                            data : oldData
                        });
                        //rowData.update({urgent:parseInt(obj.select.name)});
                        //把选择的显示数据更新到单元格中显示
                        obj.update();
                    }
                });
                layuiTableColumnEdit.render({
                    id:'#productAddTable',
                    type:'select',
                    field:'maSpecialRequirements',
                    data:selectMaSpecialRequirements,
                    callback:function (obj) {
                        console.log(obj.select); //下拉选项数据
                        console.log(obj.td); //当前单元格（td）DOM元素
                        //把选择的数据更新到行数据中
						var data = rowData.data;
                        var oldData =  table.cache["productAddTable"];
                        var i = rowData.tr.attr('data-index');
                        data.maSpecialRequirements = parseInt(obj.select.name);
                        oldData.splice(i,1,data)
                        table.reload('productAddTable',{
                            data : oldData
                        });
                        //rowData.update({urgent:parseInt(obj.select.name)});
                        //把选择的显示数据更新到单元格中显示
                        obj.update();
                    }
                });

            }
		});
        //解决前端页面排序出现的bug
        table.on('sort(productAddTable)', function(obj){
            layuiTableColumnEdit.reload("#productAddTable");//参数为表格id
        });

        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(productAddTable)', function(obj){
            rowData = obj;
        });



		//监听复选框事件
		table.on('checkbox(tableList)',function(obj){
			if(obj.checked == true && obj.type == 'all'){
				//点击全选
				$('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
			}else if(obj.checked == false && obj.type == 'all'){
				//点击全不选
				$('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
			}else if(obj.checked == true && obj.type == 'one'){
				//点击单行
				if(obj.checked == true){
					obj.tr.addClass('layui-table-click');
				}else{
					obj.tr.removeClass('layui-table-click');
				}
			}else if(obj.checked == false && obj.type == 'one'){
				//点击全选之后点击单行
				if(obj.tr.hasClass('layui-table-click')){
					obj.tr.removeClass('layui-table-click');
				}
			}
		})

        //监听行工具事件
        table.on('tool(productAddTable)', function(obj){
            var data = obj.data;
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            //单个删除
            if(obj.event === 'proDel'){
                layer.confirm('确定删除吗？', function(index){
                    //obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    var oldData =  table.cache["productAddTable"];
                    //var i = oldData.indexOf(data)
					var i = obj.tr.attr('data-index');
                    oldData.splice(i,1)
                    table.reload('productAddTable',{
                        data : oldData
                    });
                    layer.close(index);
                });
            }
        });

        //监听行修改事件
        table.on('edit(productAddTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.value); //得到修改后的值
            console.log(obj.field); //当前编辑的字段名num
            console.log(obj.data); //所在行的所有相关数据
        });
		//行点击配置
		table.on('row(tableList)', function(obj){
			var data = obj.data;
			table.reload('contenttableDetail',{
				method:'get'
				,url:'/transitOrder/transitOrderDetailList'
				,where:{"toid":data.toid}
				,page: {
					curr: 1//重新从第 1 页开始
				}
			});
		});

		//选择供应商选中id查询该供应商的所有物料
        form.on('select(sid)', function(data){
            table.reload('productAddTable',{
                data : new Array()
            });
        });

		/**
		 * 表单校验
		 */
		form.verify({
			//value：表单的值、item：表单的DOM对象
			request: function(value, item){
				if(value == '' || value == null){
					return '不能为空';
				}
			},
			//value：表单的值、item：表单的DOM对象
			sid: function(value, item){
				if(value == ''){
					return '不能为空';
				}
			},
			only: function(value, item){
				value = $.trim(value)
				if(value == '' || value == null){
					return '不能为空';
				}else{
					var tonumber = $.trim($("#tonumber").val())
					var flg = false;
					$.ajax({
						type:'post',
						data:'tonumber='+tonumber,
						url:'/transitOrder/queryAllByMution',
						dataType: 'JSON',
						async: false,
						success:function (data) {
							if(data.length == 0){
								flg  = true;
							}else if(data.length == 1){
								var ma = $.trim($("#toid").val());
								if (ma == data[0].toid) {
									flg  = true;
								}else{
									flg = false;
								}
							}else{
								flg = false;
							}
						}
					});
					if(!flg){
						return '通知单编号不能重复';
					}
				}
			}
		});

		//新增
		$("#add").click(function(){
			layer.open({
				type: 1 					//Page层类型
				,area: ['1000px', ''] 	//宽  高
				,title: '新增'
				,shade: 0.6 				//遮罩透明度
				,maxmin: true 				//允许全屏最小化
				,anim: 1 					//0-6的动画形式，-1不开启
				,content:$('#addDivID')
				,success: function(){
					addSelect();
					$("#toid").val("")
					//初始化数据
					$("#addFormID").find('input[class=layui-input],select').each(function() {
						$(this).val('');
					});
					var timestamp = (new Date()).getTime();
                    $("#tonumber").val("TZD-"+timestamp);
					table.reload('productAddTable',{
                        data : new Array()
                    });
					form.render();
				}
			});
		});
		//批量删除
		$("#del").click(function(){
			var rowData = table.checkStatus('contenttable');
			var data = rowData.data;
			var idArr = new Array();
			if(data.length == 0){
				layer.alert("请至少选择一条记录！",{icon :5});
			} else {
				var ids="";
				for(var i=0;i<data.length;i++){
                    if (data[i].tostare != 0) {
                        layer.alert("对不起，已操作的数据不能删除！",{icon :5});
                        return;
                    }
					if(ids == ""){
						ids += data[i].toid;
					}else{
						ids += "," + data[i].toid;
					}
				}
				layer.confirm('确定删除吗？', function(){
					$.ajax({
						type:'post',
						url:'/transitOrder/delete',
						data:{"ids" : ids},
						dataType:"json",
						success:function(data){
							if(data > 0){
								layer.msg("删除成功！",{icon:6});
								layer.closeAll();
								table.reload('contenttable',{
									method:'get',
									page: {
										curr: 1//重新从第 1 页开始
									}
								});
							}else{
								layer.msg("删除失败！",{icon:5});
								layer.closeAll();
								table.reload('contenttable',{
									method:'get',
									page: {
										curr: 1//重新从第 1 页开始
									}
								});
							}

						}
					});
				});
			}
		});
		/**
         * 添加弹框中，选择物料后，点提交，带回的操作
         */
        form.on('submit(productform)', function (data) {
            var flag;
            var oldData = table.cache["productAddTable"];
            var checkStatus = table.checkStatus('productTable')
            //选中的物料
            var data = checkStatus.data;
            for (var j = 0; j < data.length; j++) {
                for (var k = 0; k < oldData.length; k++) {
                    if (oldData[k].maId == data[j].maId) {
                        flag = 0;
                    }
                }
            }
            if (flag != 0) {
                for (var i = 0; i < data.length; i++) {
                    data[i].material.todremark1 =  data[i].material.remark03

					var dataArr = arrSelect.filter(function(item){
                        return item.todremark1 == data[i].material.todremark1;
                    })
                    if(dataArr.length == 1){
                        data[i].material.urgent =  dataArr[0].urgent
                        data[i].material.todremark =  dataArr[0].todremark
                    }else{
                        data[i].material.urgent =  selectUrgent[0].name
                        data[i].material.todremark =  selectTodremark[0].name
                    }
                    oldData.push(data[i].material);
                }
            } else {
                layer.msg("记录已经存在，不能重复添加",{icon:5});
            }
            table.reload('productAddTable',{
                data : oldData
            });
            $('[lay-id="productAddTable"] [data-edit="text"]:first').click();
            layer.close(productIndex)
            return false;
        });
		/**
		 * 通用表单提交(AJAX方式)
		 */
		form.on('submit(addForm)', function () {
			var index = layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});
            //获取明细中数据
            var oldData = table.cache["productAddTable"];
            var data = oldData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                return !re.test(item.todnum) || item.todnum == "";
            })
			if(oldData.length == 0){
                layer.msg("请添加物料详情！",{icon:5});
                return false;
            } else if (data.length > 0){
                layer.msg("请输入正确数量(大于0的正整数)",{icon:5});
                return false;
            } else {
				var title = "新增";
				var url = '/transitOrder/insert';
				var mids = new Array();
				var todnums = new Array();
				var todSprayingRequirements = new Array();
				var todSpecialRequirements = new Array();
				var todremark = new Array();
				var todremark1 = new Array();
				var urgent = new Array();
				for (var i = 0; i < oldData.length; i++) {
					mids.push(oldData[i].maId)
					todnums.push(oldData[i].todnum)
					todSprayingRequirements.push(oldData[i].maSprayingRequirements)
					todSpecialRequirements.push(oldData[i].maSpecialRequirements)
                    todremark.push(oldData[i].todremark)
                    todremark1.push(oldData[i].todremark1)
					urgent.push(oldData[i].urgent)
				}
				$.ajax({
					type:'post',
					url:url,
					data:$("#addFormID").serialize()+"&mids="+mids
					+"&todnums="+todnums+"&todSprayingRequirements="
					+todSprayingRequirements+"&todSpecialRequirements="+todSpecialRequirements
                    +"&urgent="+urgent+"&todremark="+todremark+"&todremark1="+todremark1,
					cache:false,
					success:function(data){
						if (data > 0) {
							layer.msg(title+'成功！',{icon:6});
							layer.closeAll();
							table.reload('contenttable',{
								method:'get',
								page: {
									curr: 1//重新从第 1 页开始
								}
							});
						} else {
							layer.msg('通知单编号重复,请重新输入！',{icon:5});
							layer.close(index);
						}
					}
				});
				return false;
			}
		})



		/*================点击选择物料的弹框================*/
        $("#addProduct").click(function(){
			if ($("#sid").val() == "" || $("#sid").val() == null) {
				layer.msg("请选择供应商！",{icon:5});
			}else if($("#tonumber").val().trim() == ""){
				layer.msg("请输入通知单编号！",{icon:5});
			} else {
				productIndex = layer.open({
					type: 1 					//Page层类型
					,area: ['900px', ''] 	//宽  高
					,title: '物料清单'
					,shade: 0.6 				//遮罩透明度
					,maxmin: true 				//允许全屏最小化
					,anim: 1 					//0-6的动画形式，-1不开启
					,content: $('#productDiv')
					,end: function () {
						var formDiv = document.getElementById('productDiv');
						formDiv.style.display = '';
					}
					,success: function () {
						var sid = $("#sid").val();
						table.render({
							elem: '#productTable'
							,id:'productTable'
							,url:'/materialDetail/list?sid='+sid
							,limits:[10,20,30]
                            ,request: {   //如果无需自定义请求参数，可不加该参数
                                pageName: 'page' //页码的参数名称，默认：page
                                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                            }
                            ,response: {   //如果无需自定义数据响应名称，可不加该参数
                                countName: 'total' //规定数据总数的字段名称，默认：count
                                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
                            }
							,defaultToolbar:['filter', 'print']
							,cols: [
								[{type: 'checkbox',fixed: 'left'}
								,{field:'mdid', title:'序号', sort: true, type:'numbers', width: 60}
								,{field:'material.maNumber', title:'图号'
									,templet: function(d){
										var value = "";
										if(d.material != null){
											value = d.material.maNumber
										}
										return value;
									},
								}
								,{field:'material.maName', title:'产品名称'
									,templet: function(d){
										var value = "";
										if(d.material != null){
											value = d.material.maName
										}
										return value;
									},
								}
								,{field:'supplier.sname', title:'供应商名称'
									,templet: function(d){
										var value = "";
										if(d.supplier != null){
											value = d.supplier.sname
										}
										return value;
									},
								}
								,{field:'supplier.snumber', title:'供应商编号'
									,templet: function(d){
										var value = "";
										if(d.supplier != null){
											value = d.supplier.snumber
										}
										return value;
									},
								}
								]
							]
							,page: true
						});
					}
				});
			}
		});

	});
	function addSelect() {
		$('#sid').empty();
		//下拉框查找所有供应商
		$.ajax({
			type: 'POST',
			url: '/supplier/queryAllByMution',
			dataType: 'json',
			async: false,
			success: function (datas){
				for (var i = 0; i < datas.length; i++) {
					$("#sid").append("<option value='"+ datas[i].sid +"'>"+ datas[i].sname +"</option>");
				}
			}
		});
	}

</script>
</body>
</html>
